//
//  PYCatalogueManager.m
//  IHome
//
//   Created by zhujizheng on 2020/2/18.
//  Copyright © 2019年 com.zhujizheng. All rights reserved.
//

#import "PYCatalogueManager.h"
#import "PYImageManager.h"
@implementation PYCatalogueManager

+ (NSArray<PYCatalogue *> *)getCatalogueWithFullPath:(NSString *)fullPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:fullPath error:&error];
    NSMutableArray *dataArray = [NSMutableArray array];
    BOOL isDirectory = NO;
    for (NSString *fileName in fileList) {
        NSString *filePath = [fullPath stringByAppendingPathComponent:fileName];
        [fileManager fileExistsAtPath:filePath isDirectory:(&isDirectory)];
        PYCatalogue *data = [PYCatalogue new];
        data.name = fileName;
        data.fullPath = filePath;
        NSString *extension = [[fileName pathExtension] lowercaseString];
        if([extension isEqualToString:@"jpg"] || [extension isEqualToString:@"gif"] || [extension isEqualToString:@"png"] || [extension isEqualToString:@"jpeg"] || [extension isEqualToString:@"bmp"]){
            data.type = PYFileTypeImage;
        } else if ([extension isEqualToString:@"mp4"] || [extension isEqualToString:@"mov"] || [extension isEqualToString:@"m4v"]) {
            data.type = PYFileTypeVideo;
        } else if ([extension isEqualToString:@"plist"]) {
            data.type = PYFileTypePlist;
        } else if ([extension isEqualToString:@"zip"]) {
            data.type = PYFileTypeZip;
        } else if ([extension isEqualToString:@"mk"]) {
            data.type = PYFileTypeLog;
        } else if ([extension isEqualToString:@"db"]) {
            data.type = PYFileTypeDB;
        } else if ([extension isEqualToString:@"sqlite"]) {
            data.type = PYFileTypeSqlite;
        } else {
            if (isDirectory) {
                data.type = PYFileTypeDirectory;
            } else {
                NSData *fileData = [NSData dataWithContentsOfFile:data.fullPath];
                PYImageType type = PYImageTypeFromData(fileData);
                if (type != PYImageTypeNone) {
                    data.type = PYFileTypeImage;
                } else {
                    data.type = PYFileTypeUnknow;
                }
            }
        }
        
        [dataArray addObject:data];
    }
    // 排序
    NSStringCompareOptions options = NSCaseInsensitiveSearch | NSNumericSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch;
    NSComparator sort = ^(PYCatalogue *obj1, PYCatalogue *obj2) {
        NSRange range = NSMakeRange(0, obj1.name.length);
        return [obj1.name compare:obj2.name options:options range:range];
    };
    NSArray *resultArray = [dataArray sortedArrayUsingComparator:sort];
    NSLog(@"字符串数组排序结果%@", resultArray);
    return resultArray;
}


@end
